package Utils;

import net.sf.json.JSONObject;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by huyong on 2016/6/16.
 */
public class RequestUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(RequestUtil.class);

    private RequestUtil() {}


    /**
     * request的全部参数转换成map
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
    public static Map<String, String[]> getMap(HttpServletRequest request){

        return request.getParameterMap();
    }

    /**
     * 把request转为map
     *
     * @param request
     * @return
     */
    public static    Map<String, Object> getParameterMap(HttpServletRequest request) {
        // 参数Map
        Map<?, ?> properties = request.getParameterMap();
        // 返回值Map
        Map<String, Object> returnMap = new HashMap<String, Object>();
        Iterator<?> entries = properties.entrySet().iterator();

        Map.Entry<String, Object> entry;
        String name = "";
        String value = "";
        Object valueObj =null;
        while (entries.hasNext()) {
            entry = (Map.Entry<String, Object>) entries.next();
            name = (String) entry.getKey();
            valueObj = entry.getValue();
            if (null == valueObj) {
                value = "";
            } else if (valueObj instanceof String[]) {
                String[] values = (String[]) valueObj;
                for (int i = 0; i < values.length; i++) {
                    value = values[i] + ",";
                }
                value = value.substring(0, value.length() - 1);
            } else {
                value = valueObj.toString();
            }
            returnMap.put(name, value);
        }
        return returnMap;
    }

    public static Map<String, Object> getMapfrompost(HttpServletRequest request){

        Map<String,Object> params = new HashMap<String, Object>();
        BufferedReader br;
        try {
            br = request.getReader();
            String str, wholeStr = "";
            while((str = br.readLine()) != null){
                wholeStr += str;
            }
            if(StringUtils.isNotEmpty(wholeStr)){
//                params = JSON.parseObject(wholeStr,Map.class);
                params=  GsonUtil.GsonToMaps(wholeStr);
            }
        } catch (
                IOException e1) {
            LOGGER.error(""+e1);
        }
        return params;

    }



    /**
     * request的部分参数转换成map：
     * 根据的keys指定的的Key从request取出值放到Map中
     * @param request
     * @param keys 需要转的key,多个key用豆号隔开
     * @return
     */
    public static Map<String,Object> getMap(HttpServletRequest request, String keys){
        String[] split = keys.split(",");
        Map<String,Object> map = new HashMap<String, Object>(split.length);
        for (String key : split) {
            map.put(key, request.getParameter(key));
        }
        return map;
    }

    /**
     * 解析JSONObject对象转换为 map
     * @param keys
     * @param MainJsonObj
     * @return
     */
    public static Map<String,Object> getMap(String keys,JSONObject MainJsonObj){
        String[] split = keys.split(",");
        Map<String,Object> map = new HashMap<String, Object>(split.length);
        for(String key:split){
            map.put(key,MainJsonObj.getString(key));
        }
        return map;
    }

    /**
     * 将map转换成bean对象：
     * 根据Map的keyValues创建Bean对象
     * @param theClass
     * @param keyValues
     * @return
     */
    public static <T> T getBean(Class<T> theClass,Map<String,Object> keyValues){
        T bean = null;
        try {
            bean = theClass.newInstance();
            BeanUtils.populate(bean, keyValues);
        } catch (Exception e) {
            LOGGER.error("map转换成bean对象出错", e);
        }
        return bean;
    }
}